//
//  ZHSegmentView.swift
//  ZHPageView
//
//  Created by Rango on 2020/8/27.
//  Copyright © 2020 Rango. All rights reserved.
//

import UIKit

class ZHSegmentView: UIView {
    // MARK: - ---> Public
    var didTapClosure: ((Int, Bool) -> Void)?
    var didExtraBtnActionClosure: ((UIView) -> Void)?
    var isHiddenExtraBtn: Bool = false {
        didSet {
            extraBtnView.isHidden = isHiddenExtraBtn
        }
    }
    
    /// 设置选中下标
    /// - Parameters:
    ///   - index: 下标
    ///   - animated: true 动画; false 无切换动画; 默认 true
    public func resetSelectedIndex(_ index: Int, animated: Bool = true) {
        didTapClosure?(index, animated)
    }
    /// 居中选中标题 默认 isScroll = false
    /// - Parameters:
    ///   - index: index description
    ///   - isScroll: true 拖拽; false 点击; 默认 false
    public func centerSeledted(with index: Int, isScroll: Bool = false, animated: Bool = true) {
        centerTitle(with: index, isScroll: isScroll, animated: animated)
    }
    /// 渐进式改变标题状态
    /// - Parameters:
    ///   - progress: 0 ~ 1
    ///   - isScroll: true 拖拽; false 点击; 默认 false
    ///   - direction: direction description
    public func scrollStatus(with progress: CGFloat, isScroll: Bool = false, direction: ZHScrollDirection) {
        progressive(with: progress, isScroll: isScroll, direction: direction)
    }
    
    // MARK: - ---> Private
    private var style: ZHSegmentStyle = ZHSegmentStyle()
    private var titles: [String] = []
    private var itemViews: [UIView] = []
    private var itemWidths: [CGFloat] = []
    private var sWidth: CGFloat { segmentView.frame.width }
    private var sHeight: CGFloat { segmentView.frame.height }
    private var lastIndex: Int = 0
    private var isFirstAdd: Bool = true
    // MARK: - ---> Life Cycle
    
    /// 初始化
    /// - Parameters:
    ///   - frame: frame description
    ///   - style: style description
    ///   - titles: titles description
    init(frame: CGRect,
         style: ZHSegmentStyle,
         titles: [String]) {
        super.init(frame: frame)
        
        self.titles = titles
        self.style = style
        self.lastIndex = style.defaultIndex
        
        initSubviews()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        initSubviews()
        fatalError("init(coder:) has not been implemented")
    }
    deinit {
        print("\(#file)-\(#line)-\(#function)--->销毁")
    }
    /// 布局子视图
    override func layoutSubviews() {
        super.layoutSubviews()
        // TODO: 布局子视图
        let kWidth = bounds.width
        let kHeight = bounds.height
        var extraBtnViewW: CGFloat = kHeight

        if style.isShowExtraBtn {
            let extraBtnViewY: CGFloat = 0
            let extraBtnViewH: CGFloat = kHeight
            let extraBtnViewX: CGFloat = kWidth - extraBtnViewW
            extraBtnView.frame = CGRect(x: extraBtnViewX, y: extraBtnViewY, width: extraBtnViewW, height: extraBtnViewH)
        } else {
            extraBtnViewW = 0
        }

        let segmentViewX: CGFloat = style.edgeInset.left
        let segmentViewY: CGFloat = 0
        let segmentViewW: CGFloat = kWidth - extraBtnViewW - segmentViewX + style.edgeInset.right
        let segmentViewH: CGFloat = kHeight
        segmentView.frame = CGRect(x: segmentViewX, y: segmentViewY, width: segmentViewW, height: segmentViewH)
        
        segmentLayoutSubviews()
        
        if style.isShowIndicator {
            indicatorLayoutSubviews()
        }
        
        isFirstAdd = false
    }
    /// 初始化子视图
    private func initSubviews() {
        // TODO: 初始化子视图
        backgroundColor = style.bgColor
        if style.isShowExtraBtn {
            addSubview(extraBtnView)
        }
        addSubview(segmentView)
        if style.isShowIndicator {
            segmentView.insertSubview(indicator, at: 0)
        }
        setUpSegmentView()
    }
    // MARK: - ---> Lazy
    /// 指示器
    private lazy var indicator: UIView = {
        var indicator = UIView()
        switch style.indicatorType {
        case .custom:
            indicator = style.indicatorCustomView
        default:
            break
        }
        indicator.backgroundColor = style.indicatorColor
        if style.indicatorCornerRadius > 0.5 * style.indicatorHeight {
            indicator.layer.cornerRadius = style.indicatorHeight * 0.5
        } else {
            indicator.layer.cornerRadius = style.indicatorCornerRadius
        }
        if style.isIndicatorBorder {
            indicator.layer.borderColor = style.indicatorBorderColor.cgColor
            indicator.layer.borderWidth = style.indicatorBorderWidth
        }
        return indicator
    }()
    /// 分页区
    private lazy var segmentView: UIScrollView = {
        $0.showsVerticalScrollIndicator = false
        $0.showsHorizontalScrollIndicator = false
        $0.bounces = style.isTitleBounces
        return $0
    }(UIScrollView())
    private lazy var extraBtnView: ZHExtraBtnView = {
        $0.backgroundColor = style.extraBtnBgColor
        $0.bgImg = style.extraBtnBgImg
        $0.title = style.extraBtnTitle
        $0.textColor = style.extraBtnTextColor
        $0.didExtraBtnActionClosure = { [weak self] item in
            guard let strongSelf = self else { return }
            strongSelf.didExtraBtnActionClosure?(item)
        }
        return $0
    }(ZHExtraBtnView())
}

extension ZHSegmentView {
    // 布局指示器
    private func indicatorLayoutSubviews() {
        let aX: CGFloat = 0
        let aW: CGFloat = indicatorWidth(lastIndex)
        let aH: CGFloat = style.indicatorHeight
        let aY: CGFloat = sHeight - aH - style.indicatorPadding
        indicator.frame = CGRect(x: aX, y: aY, width: aW, height: aH)
        
        if lastIndex < itemWidths.count {
            let item = itemViews[lastIndex]
            indicator.center.x = item.center.x
        }
    }
    // 布局子视图,适配横竖屏切换
    private func segmentLayoutSubviews() {
        var aX: CGFloat = 0
        let aY: CGFloat = 0
        var aW: CGFloat = 0
        let aH: CGFloat = sHeight
        for item in itemViews.enumerated() {
            aW = itemWidths[item.offset]
            aX += item.offset == 0 ? 0 : itemWidths[item.offset - 1]
            if isFirstAdd {
                item.element.frame = CGRect(x: aX, y: aY, width: aW, height: aH)
                if item.offset == style.defaultIndex {
                    centerTitle(with: style.defaultIndex, isScroll: false, animated: false)
                }
            } else {
                if item.offset == lastIndex {
                    centerTitle(with: lastIndex, isScroll: false, animated: false)
                } else {
                    item.element.frame = CGRect(x: aX, y: aY, width: aW, height: aH)
                }
            }
        }
        
        let width = itemWidths.reduce(0, +)
        segmentView.contentSize = CGSize(width: width, height: 0)
    }
    private func setUpSegmentView() {
        itemWidths.removeAll()
        for item in titles.enumerated() {
            let label = ZHItemLabel()
            label.text = item.element
            label.tag = item.offset
            label.font = style.titleFont
            label.textColor = style.titleColor
            label.scale = style.titleScale
            label.startColor = style.titleColor
            label.endColor = style.titleSelectedColor
            label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(segmentItemTap(_ :))))
            label.isUserInteractionEnabled = true
            segmentView.addSubview(label)
            itemViews.append(label)
            
            if style.isAutoTitleWidth { // 自动宽度
                label.sizeToFit()
                itemWidths.append(label.frame.width + 2 * style.titleMargin)
            } else {
                itemWidths.append(style.titleWidth + 2 * style.titleMargin) // 等宽
            }
            
            if item.offset == style.defaultIndex { // 初始值
                label.textColor = style.titleSelectedColor
            }
        }
    }
    @objc private func segmentItemTap(_ tap: UITapGestureRecognizer) {
        if let index = tap.view?.tag {
            didTapClosure?(index, true)
        }
    }
    private func indicatorWidth(_ index: Int, extra: CGFloat = 0) -> CGFloat {
        if index < itemWidths.count {
            switch style.indicatorType {
            case .cover, .custom:
                return style.isIndicatorAutoWidth ? itemWidths[index] + extra : style.indicatorWidth
            default:
                return style.isIndicatorAutoWidth ? itemWidths[index] - 2 * style.titleMargin + extra : style.indicatorWidth
            }
        } else {
            return 0
        }
    }
    
    // 居中标题
    private func centerTitle(with index: Int, isScroll: Bool = false, animated: Bool = true) {
        //self.isScroll = isScroll
        lastIndex = index
        // 保证标题居中
        if let label = itemViews[lastIndex] as? ZHItemLabel {
            var offsetX = label.center.x - sWidth / 2
            if offsetX < 0 { offsetX = 0 } // 左边界
            var maxX = segmentView.contentSize.width - sWidth
            if maxX < 0 { maxX = 0 }
            if offsetX > maxX { offsetX = maxX } // 右边界
            segmentView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
            
            // 保证标题最后状态正常
            for item in itemViews {
                if let item = item as? ZHItemLabel {
                    if item != label { // 回复默认状态
                        if isScroll { // 拖拽过来的
                            item.zoomTitle(with: 0, animated: true)
                            item.textColor = style.titleColor
                        } else { // 点选过来的
                            if style.isScaleTitle {
                                item.zoomTitle(with: 0, animated: true)
                            }
                            if style.isGradientTitleColor {
                                item.gradientColor(with: 0, animated: true)
                            } else {
                                item.textColor = style.titleColor
                            }
                        }
                    } else { // 选中的
                        if isScroll { // 拖拽过来的
                            if style.isScaleTitle {
                                item.zoomTitle(with: 1, animated: true)
                            }
                            item.textColor = style.titleSelectedColor
                        } else { // 点选过来的
                            if style.isScaleTitle {
                                item.zoomTitle(with: 1, animated: true)
                            }
                            if style.isGradientTitleColor {
                                item.gradientColor(with: 1, animated: true)
                            } else {
                                item.textColor = style.titleSelectedColor
                            }
                        }
                    }
                }
            }
            if isScroll {
                switch style.indicatorAnimaType {
                case .end:
                    UIView.animate(withDuration: style.indicatorDuration) {
                        self.indicator.frame.size.width = self.indicatorWidth(self.lastIndex)
                        self.indicator.center.x = label.center.x
                    }
                default:
                    indicator.frame.size.width = indicatorWidth(lastIndex)
                    indicator.center.x = label.center.x
                }
            } else {
                switch style.indicatorAnimaType {
                case .none:
                    self.indicator.frame.size.width = self.indicatorWidth(self.lastIndex)
                    self.indicator.center.x = label.center.x
                default:
                    if animated {
                        UIView.animate(withDuration: style.indicatorDuration) {
                            self.indicator.frame.size.width = self.indicatorWidth(self.lastIndex)
                            self.indicator.center.x = label.center.x
                        }
                    } else {
                        self.indicator.frame.size.width = self.indicatorWidth(self.lastIndex)
                        self.indicator.center.x = label.center.x
                    }
                }
            }
        }
    }
    // 实时改变标题状态
    private func progressive(with progress: CGFloat, isScroll: Bool, direction: ZHScrollDirection) {
        //self.isScroll = isScroll
        let leftIndex = Int(progress)
        if progress > 0 && leftIndex < itemViews.count - 1 { // 边界问题
            let rightIndex = leftIndex + 1
            let rightScale = progress - CGFloat(leftIndex)
            let leftScale = 1 - rightScale
            guard let rightLabel = itemViews[rightIndex] as? ZHItemLabel,
                let leftLabel = itemViews[leftIndex] as? ZHItemLabel else {
                    return
            }
            
            if style.isScaleTitle { // 实时缩放大小
                rightLabel.zoomTitle(with: rightScale, animated: false)
                leftLabel.zoomTitle(with: leftScale, animated: false)
            }
            
            if style.isGradientTitleColor { // 实时渐变颜色
                rightLabel.gradientColor(with: rightScale, animated: false)
                leftLabel.gradientColor(with: leftScale, animated: false)
            }
            if isScroll {
                if style.isShowIndicator { // 实时改变指示器位置
                    if style.indicatorAnimaType == .default {
                        let tWidth: CGFloat = (itemWidths[rightIndex] - itemWidths[leftIndex])
                        switch direction {
                        case .left: // <<<
                            indicator.frame.size.width = indicatorWidth(rightIndex, extra: -tWidth * leftScale)
                        case .right: // >>>
                            indicator.frame.size.width = indicatorWidth(leftIndex, extra: tWidth * rightScale)
                        default:
                            break
                        }
                        indicator.center.x = leftLabel.center.x + (rightLabel.center.x - leftLabel.center.x) * rightScale
                    } else if style.indicatorType == .none {
                        
                    }
                }
            }
        } else if leftIndex == itemViews.count - 1 { // 修复右边界时,旋转屏幕导致位置错乱的问题
            centerTitle(with: leftIndex, isScroll: isScroll, animated: false)
        }
    }
}

// MARK: - 👇👇👇 ZHItemLabel 👇👇👇
extension ZHSegmentView {
    class ZHItemLabel: UILabel {
        // MARK: - ---> Public
        var scale: CGFloat = 1.2
        var startColor: UIColor = .blue
        var endColor: UIColor = .red
        
        /// 缩放标题字体大小
        /// - Parameters:
        ///   - scale: 进度 0 ~ 1
        ///   - animated: true 0.25 秒动画完成; false 渐进式改变值
        public func zoomTitle(with scale: CGFloat = 1, animated: Bool = true) {
            let transScale = 1 + scale * CGFloat(abs(self.scale - 1))
            if animated {
                UIView.animate(withDuration: 0.25) {
                    self.transform = CGAffineTransform(scaleX: transScale, y: transScale)
                }
            } else {
                self.transform = CGAffineTransform(scaleX: transScale, y: transScale)
            }
        }
        
        /// 标题颜色渐变
        /// - Parameters:
        ///   - scale: 进度 0 ~ 1
        ///   - animated: true 0.25 秒动画完成; false 渐进式改变值
        public func gradientColor(with scale: CGFloat = 1, animated: Bool = false) {
            let start = rgbComponents(startColor)
            let end = rgbComponents(endColor)
            
            let red: CGFloat = start.0 + (end.0 - start.0) * scale
            let green: CGFloat = start.1 + (end.1 - start.1) * scale
            let blue: CGFloat = start.2 + (end.2 - start.2) * scale
            
            textColor = UIColor(red: red, green: green, blue: blue, alpha: 1)
        }
        // MARK: - ---> Private
        /// 获取 RGB
        /// - Parameter color: color description
        /// - Returns: description
        private func rgbComponents(_ color: UIColor) -> (CGFloat, CGFloat, CGFloat) {
            // 颜色 r g b
            // 黑色 0 0 0
            // 红色 1 0 0
            // 绿色 0 1 0
            // 蓝色 0 0 1
            // 黄色 1 0 1
            // 白色 1 1 1
            var R: CGFloat = 0
            var G: CGFloat = 0
            var B: CGFloat = 0
            
            let num = color.cgColor.numberOfComponents
            if num == 4 {
                if let components = color.cgColor.components {
                    R = components[0]
                    G = components[1]
                    B = components[2]
                    return (R, G, B)
                } else {
                    return (R, G, B)
                }
            } else {
                return (R, G, B)
            }
        }
        // MARK: - ---> Life Cycle
        override init(frame: CGRect) {
            super.init(frame: frame)
            initSubviews()
        }
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            initSubviews()
            fatalError("init(coder:) has not been implemented")
        }
        deinit {
            //print("\(#file)-\(#line)-\(#function)--->销毁")
        }
        /// 布局子视图
        //override func layoutSubviews() {
            //super.layoutSubviews()
            // TODO: 布局子视图
            //let kWidth = bounds.width
            //let kHeight = bounds.height
        //}
        /// 初始化子视图
        private func initSubviews() {
            // TODO: 初始化子视图
            textAlignment = .center
        }
        // MARK: - ---> Lazy
    }
}
// MARK: - 👇👇👇 ZHExtraBtnView 👇👇👇
extension ZHSegmentView {
    class ZHExtraBtnView: UIView {
        // MARK: - ---> Public
        var didExtraBtnActionClosure: ((UIView) -> Void)?
        
        var title: String = "" {
            didSet {
                titleLabel.text = title
                layoutSubviews()
            }
        }
        var textColor: UIColor = .red {
            didSet {
                titleLabel.textColor = textColor
            }
        }
        var bgImg: UIImage? = nil {
            didSet {
                bgImgView.image = bgImg
                layoutSubviews()
            }
        }
        // MARK: - ---> Private
        // MARK: - ---> Life Cycle
        override init(frame: CGRect) {
            super.init(frame: frame)
            initSubviews()
        }
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            initSubviews()
            fatalError("init(coder:) has not been implemented")
        }
        deinit {
            //print("\(#file)-\(#line)-\(#function)--->销毁")
        }
        /// 布局子视图
        override func layoutSubviews() {
            super.layoutSubviews()
            // TODO: 布局子视图
            //let kWidth = bounds.width
            //let kHeight = bounds.height
            
            bgImgView.frame = bounds
            titleLabel.frame = bounds
        }
        /// 初始化子视图
        private func initSubviews() {
            // TODO: 初始化子视图
            addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap(_ :))))
            isUserInteractionEnabled = true
            addSubview(bgImgView)
            addSubview(titleLabel)
        }
        @objc private func tap(_ gesture: UITapGestureRecognizer) {
            didExtraBtnActionClosure?(self)
        }
        // MARK: - ---> Lazy
        private lazy var bgImgView: UIImageView = {
            $0.contentMode = .scaleToFill
            return $0
        }(UIImageView())
        private lazy var titleLabel: UILabel = {
            $0.text = title
            $0.textAlignment = .center
            $0.font = UIFont.systemFont(ofSize: 14, weight: .medium)
            $0.textColor = .darkGray
            return $0
        }(UILabel())
    }
}
